package com.gaodun.hk.common.utils;

import org.modelmapper.ModelMapper;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author fengyamin
 * @date 2021/01/25
 **/
public class ModelMapperUtils {
    private ModelMapperUtils() {
    }

    public static final ModelMapper MODEL_MAPPER = new ModelMapper();

    /**
     * map
     *
     * @param source          source对象
     * @param destinationType 目标类型
     * @param <D>             目标类型
     * @return 目标类型实例
     */
    public static <D> D map(Object source, Class<D> destinationType) {
        return Optional.ofNullable(source).map(s -> MODEL_MAPPER.map(source, destinationType)).orElse(null);
    }

    /**
     * map 这个方法需要谨慎的使用，尽量只用于map简单的单层对象，不要用于嵌套场景
     *
     * @param source      source
     * @param destination destination
     */
    public static void map(Object source, Object destination) {
        MODEL_MAPPER.map(source, destination);
    }

    /**
     * mapList
     *
     * @param sourceList      sourceList
     * @param destinationType destinationType
     * @param <D>             D
     * @return list of destination type
     */
    public static <D> List<D> mapList(List<? extends Object> sourceList, Class<D> destinationType) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyList();
        }
        return sourceList.stream().map(e -> map(e, destinationType)).collect(Collectors.toList());
    }
}
